package model

import (
	"classtype/classtype"

	"gorm.io/gorm"
)

type ClassTypes struct {
	gorm.Model
	Name        string `gorm:"column:name;type:varchar(20);not null;" json:"name"`
	ParentId    int32  `gorm:"column:parent_id;type:int;not null;" json:"parent_id"`
	Description string `gorm:"column:description;type:varchar(200);default:NULL;" json:"description"`
	Sort        int32  `gorm:"column:sort;type:int;default:NULL;" json:"sort"`
}

func (C *ClassTypes) BuildTree() ([]*classtype.ClassTypeTree, error) {
	var classTypes []ClassTypes
	if err := DB.Model(&ClassTypes{}).Order("sort desc").Order("created_at desc").Find(&classTypes).Error; err != nil {
		return nil, err
	}
	var ClsMap = make(map[int32][]ClassTypes)
	for _, classType := range classTypes {
		ClsMap[classType.ParentId] = append(ClsMap[classType.ParentId], classType)
	}
	tree := CreateTree(ClsMap[0], ClsMap)
	return tree, nil
}

func CreateTree(types []ClassTypes, clsMap map[int32][]ClassTypes) []*classtype.ClassTypeTree {
	var Res []*classtype.ClassTypeTree
	for _, classTypes := range types {
		var res = classtype.ClassTypeTree{
			Name:             classTypes.Name,
			Description:      classTypes.Description,
			Sort:             int64(classTypes.Sort),
			ParentId:         int64(classTypes.ParentId),
			Id:               int64(classTypes.ID),
			CliClassTypeTree: CreateTree(clsMap[int32(classTypes.ID)], clsMap),
		}
		Res = append(Res, &res)
	}
	return Res
}
